#!/usr/bin/env coffee

import _crypto from 'crypto'
import {binary} from '../const.mjs'

AES = "aes-256-ccm"
authTagLength = 4

export encrypt = (key, data, ivlen=7) ->
  iv = _crypto.randomBytes(ivlen)
  cipher = _crypto.createCipheriv(AES, key, iv, {
    authTagLength
  })
  encrypted = Buffer.concat([
    cipher.update(data,binary)
    cipher.final()
  ])
  tag = cipher.getAuthTag()
  Buffer.concat([
    iv
    tag
    encrypted
  ])

export decrypt = (key, data, ivlen=7) ->
  iv = data.slice(0, ivlen)
  tagend = ivlen+authTagLength
  tag = data.slice(ivlen, tagend)
  data = data.slice(tagend)
  decipher = _crypto.createDecipheriv(AES, key, iv,{
    authTagLength
  })
  decipher.setAuthTag tag
  Buffer.concat [
    decipher.update(data,binary)
    decipher.final()
  ]

# import {AES_KEY} from '../const/v'
#
# t =  _crypto.randomBytes(30)
# console.log t
# # The length of the initialization vector (iv) N must be between 7 and 13 bytes (7 ≤ N ≤ 13)
# ivl = 7
# b = encrypt(AES_KEY, ivl, t)
# console.log b.length
# console.log decrypt(AES_KEY, ivl, b)
